import {useState, useEffect} from 'react';
import jatsXsltString from "../../../../assets/jats_to_html.xsl";
import doiBatchXsltString from "../../../../assets/doi_to_html.xsl";
import tablePlaceholderImgUrl from "../../../../assets/img/table-icon.gif"
import {useIntl} from "umi";

type JatshtmlResult = {
  all?: string,
  abstrCn?: string,
  abstrEn?: string,
  fulltext?: string,
  reference?: string,
  referenceTotal?: number,
  chart?: string,
  chartTotal?: number,
}

interface JatsTransformerParam {
  xmlUrl?: string,            //xml文件下载地址
  imgUrlPrefix?: string,      //图片前缀(已废弃)
}

interface JatsTransformerResult {
  htmlResult?: JatshtmlResult;
  error?: Error;
  loading: boolean;
}

const useJatsTransformer = (param?: JatsTransformerParam): JatsTransformerResult => {
  const [htmlResult, setHtmlResult] = useState<JatshtmlResult | undefined>();
  const [error, setError] = useState<Error | undefined>();
  const [loading, setIsLoading] = useState(true);
  const intl= useIntl();

  useEffect(() => {
    const transformJats = async () => {
      try {
        setIsLoading(true);
        // 创建一个超时的 Promise
        const timeoutPromise = new Promise((_, reject) => {
          setTimeout(() => reject(new Error('请求超时')), 5000); // 超时时间设置为 5000 毫秒（5 秒）
        });

        // 使用 Promise.race 实现超时控制
        const xmlResponse = await Promise.race([
          fetch(`${param?.xmlUrl}`), // 原始的 fetch 请求
          timeoutPromise,           // 超时逻辑
        ]) as Response;

        if (!xmlResponse.ok) {
          throw new Error(`XSLT 文件加载失败: ${xmlResponse.status}`);
        }
        const xmlText = await xmlResponse.text();
        // 解析 XML 和 XSLT（直接使用导入的字符串）
        const parser = new DOMParser();

        const xmlDoc = parser.parseFromString(xmlText, 'text/xml');
        // xmlDoc 有2种, 除去最前面的 <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE .../>申明
        // 1,  开头是 <article ...
        // 2,  开头是 <doi_batch ...>
        const isJatsXml = xmlDoc.documentElement.tagName === 'article';

        //XSLT, 2种格式用各自的xslt
        const xsltDoc = parser.parseFromString(isJatsXml ? jatsXsltString : doiBatchXsltString, 'text/xml');

        // 创建 XSLT 处理器
        const processor = new XSLTProcessor();
        processor.importStylesheet(xsltDoc);
        // 设置参数
        processor.setParameter(null, 'tablePlaceholderImgUrl', tablePlaceholderImgUrl);
        processor.setParameter(null, 'clickToJumpText', intl.formatMessage({ id: 'text.click-to-jump' }));
        if (param?.imgUrlPrefix) {
          processor.setParameter(null, 'imgUrlPrefix', param.imgUrlPrefix);
        }

        // 执行转换
        const resultDoc = processor.transformToDocument(xmlDoc);
        const serializer = new XMLSerializer();
        const htmlResult = serializer.serializeToString(resultDoc);

        // 提取中/英语言的摘要
        const abstrDefault = resultDoc.querySelector('div.article-front div.metadata-abstract-default');
        const abstrCn = resultDoc.querySelector('div.article-front div.metadata-abstract-cn, div.article-front div.metadata-abstract-zh') || abstrDefault;
        const abstrEn = resultDoc.querySelector('div.article-front div.metadata-abstract-en') || abstrDefault;

        // 提取图表
        const chartElements = resultDoc.querySelectorAll('div.article-body div.panel');
        let chartsHtml = '';
        chartElements.forEach(element => {
          chartsHtml += element.outerHTML;
        });

        const fulltext = resultDoc.querySelector('div.article-body')?.outerHTML;
        setHtmlResult({
          all: htmlResult,
          abstrCn: abstrCn?.outerHTML,
          abstrEn: abstrEn?.outerHTML,
          fulltext: fulltext,
          reference: isJatsXml ? resultDoc.querySelector('div.article-back div.ref-list.table')?.outerHTML : fulltext,    //<doi_batch>的全都是fulltext
          referenceTotal: isJatsXml ? resultDoc.querySelectorAll('div.article-back div.ref-list.table>.row')?.length : undefined,
          chart: isJatsXml ? chartsHtml : fulltext, //<doi_batch>的全都是fulltext
          chartTotal: isJatsXml ? chartElements.length : undefined,
        });
        console.log(htmlResult)
        setError(undefined);
      } catch (err) {
        console.log(err)
        setError(err as Error);
        setHtmlResult(undefined);
      } finally {
        setIsLoading(false);
      }
    };

    if (param?.xmlUrl) {
      transformJats();
    } else {
      setError(new Error('JATS URL 为空'));
      setIsLoading(false);
    }
  }, [param?.xmlUrl, param?.imgUrlPrefix]);

  return {htmlResult, error, loading};
};

export default useJatsTransformer;
